<script setup>
import { Plus, Edit, Delete, User, Refresh } from '@element-plus/icons-vue'
import { onMounted, ref, onActivated, nextTick } from 'vue'
import { getDishListAPI } from '@/api/dish'
import { getUserListAPI } from '@/api/user'
import { getMerchantListAPI } from '@/api/merchant'
import { getIngredientListAPI } from '@/api/ingredient'
import { getAdminLogListAPI } from '@/api/log'

// 统计数据
const stats = ref({
  totalVisits: 0,
  totalUsers: 0,
  totalMerchants: 0,
  totalDishes: 0,
  totalIngredients: 0
})

// 小程序运行时间相关
const launchTime = new Date('2025-08-21T10:30:00') // 小程序启动时间
const runningTime = ref({
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0
})

// 日志相关状态
const logData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalLogs = ref(0)
const logLoading = ref(true)
const loadingMore = ref(false)
const hasMore = ref(true)
const timelineContainer = ref(null)

// operatorId到管理员名称的映射
const operatorMap = {
  1: 'Admin-1',
  2: 'Admin-2',
  3: 'Admin-3',
  4: 'Admin-4',
  5: 'Admin-5'
}

// 操作类型到图标和颜色的映射
const operationTypeMap = {
  新增: { icon: Plus, color: '#67c23a', type: 'add' },
  修改: { icon: Edit, color: '#409eff', type: 'edit' },
  删除: { icon: Delete, color: '#f56c6c', type: 'delete' },
  登录: { icon: User, color: '#909399', type: 'register' }
}

// 计算小程序运行时间
const calculateRunningTime = () => {
  const now = new Date()
  const diffMs = now - launchTime

  // 计算天、时、分、秒
  const totalSeconds = Math.floor(diffMs / 1000)
  const days = Math.floor(totalSeconds / (60 * 60 * 24))
  const remainingSeconds = totalSeconds % (60 * 60 * 24)
  const hours = Math.floor(remainingSeconds / (60 * 60))
  const remainingMinutes = remainingSeconds % (60 * 60)
  const minutes = Math.floor(remainingMinutes / 60)
  const seconds = remainingMinutes % 60

  runningTime.value = { days, hours, minutes, seconds }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const [dishRes, userRes, merchantRes, ingredientRes] = await Promise.all([
      getDishListAPI(),
      getUserListAPI(),
      getMerchantListAPI(),
      getIngredientListAPI()
    ])

    stats.value = {
      totalUsers: userRes.data.data.total,
      totalMerchants: merchantRes.data.data.total,
      totalDishes: dishRes.data.data.total,
      totalIngredients: ingredientRes.data.data.total
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 解析params参数
const parseParams = (paramsStr) => {
  try {
    if (!paramsStr) return null
    // 处理可能的格式问题
    const cleaned = paramsStr.replace(
      /([{,])\s*([a-zA-Z0-9_]+?)\s*:/g,
      '$1"$2":'
    )
    return JSON.parse(cleaned)
  } catch (error) {
    console.error('解析params失败:', error, '原始数据:', paramsStr)
    return null
  }
}

// 生成操作内容文本
const generateContent = (record, operatorName) => {
  const params = parseParams(record.params)
  const operation = record.operation
  let content = `${operatorName} ${operation}`

  // 根据不同操作类型生成更详细的内容
  if (operation.includes('新增菜品') && params && params[0]) {
    const dish = params[0]
    content = `${operatorName} 新增了菜品"${dish.dishName || '未知菜品'}"`
  } else if (operation.includes('添加商家') && params && params[0]) {
    const merchant = params[0]
    content = `${operatorName} 添加了商家"${merchant.merchantName || '未知商家'}"`
  } else if (operation.includes('添加材料') && params && params[0]) {
    const ingredient = params[0]
    content = `${operatorName} 添加了材料"${ingredient.name || '未知材料'}"`
  } else if (operation.includes('修改菜品') && params && params[0]) {
    const dish = params[0]
    content = `${operatorName} 修改了菜品"${dish.dishName || `#${dish.id}`}"`
  } else if (operation.includes('修改材料') && params && params[0]) {
    const ingredient = params[0]
    content = `${operatorName} 修改了材料"${ingredient.name || `#${ingredient.id}`}"`
  } else if (operation.includes('更新商家信息') && params && params[0]) {
    const merchant = params[0]
    content = `${operatorName} 更新了商家"${merchant.merchantName || `#${merchant.id}`}"的信息`
  } else if (operation.includes('修改用户反馈') && params && params[0]) {
    const feedback = params[0]
    content = `${operatorName} 修改了反馈#${feedback.id || '未知'}`
  } else if (operation.includes('删除反馈') && params) {
    const feedbackId = Array.isArray(params) ? params[0] : params.id
    content = `${operatorName} 删除了反馈#${feedbackId}`
  } else if (operation.includes('员工登入')) {
    if (record.errorMsg) {
      content = `${operatorName} 登录失败 ：${record.errorMsg}`
    } else {
      content = `${operatorName} 登录成功`
    }
  }

  return content
}

// 确定操作类别
const determineCategory = (operation) => {
  if (operation.includes('菜品')) return 'dish'
  if (operation.includes('商家')) return 'shop'
  if (operation.includes('材料')) return 'ingredient'
  if (operation.includes('反馈')) return 'feedback'
  if (operation.includes('员工登入')) return 'user'

  return 'other'
}

// 获取操作类型配置
const getOperationConfig = (operation) => {
  if (operation.includes('新增') || operation.includes('添加')) {
    return operationTypeMap['新增']
  } else if (operation.includes('修改') || operation.includes('更新')) {
    return operationTypeMap['修改']
  } else if (operation.includes('删除')) {
    return operationTypeMap['删除']
  } else if (operation.includes('员工登入')) {
    return operationTypeMap['登录']
  }

  return { icon: User, color: '#909399', type: 'view' }
}

// 格式化时间显示
const formatTime = (timeString) => {
  if (!timeString) return ''

  const now = new Date()
  const logTime = new Date(timeString)
  const diffMs = now - logTime
  const diffMinutes = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMinutes / 60)
  const diffDays = Math.floor(diffHours / 24)

  if (diffMinutes < 1) {
    return '刚刚'
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else if (diffHours < 24) {
    return `${diffHours}小时前`
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    // 超过一周的时间显示具体日期
    return timeString.split(' ')[0]
  }
}

// 获取日志信息并格式化
const fetchLogs = async (page = 1, append = false) => {
  // 如果是加载更多且正在加载中，则返回
  if (append && loadingMore.value) return

  // 设置加载状态
  if (append) {
    loadingMore.value = true
  } else {
    logLoading.value = true
  }

  try {
    const res = await getAdminLogListAPI(page, pageSize.value)

    if (res.data.code === 1 && res.data.data) {
      totalLogs.value = res.data.data.total
      const newLogs = res.data.data.records.map((record) => {
        const opConfig = getOperationConfig(record.operation)
        const formattedTime = formatTime(record.createTime)
        const category = determineCategory(record.operation)

        return {
          id: record.id,
          content: generateContent(
            record,
            operatorMap[record.operatorId] || '未知管理员'
          ),
          timestamp: formattedTime,
          originalTime: record.createTime,
          type: opConfig.type,
          icon: opConfig.icon,
          color: opConfig.color,
          category: category,
          hasError: !!record.errorMsg
        }
      })

      // 如果是加载更多则追加数据，否则替换数据
      if (append) {
        logData.value = [...logData.value, ...newLogs]
      } else {
        logData.value = newLogs
      }

      // 判断是否还有更多数据
      hasMore.value = logData.value.length < totalLogs.value
    }
  } catch (error) {
    console.error('获取日志数据失败:', error)
  } finally {
    // 重置加载状态
    logLoading.value = false
    loadingMore.value = false
  }
}

// 初始加载日志
const loadInitialLogs = () => {
  currentPage.value = 1
  fetchLogs(1, false)
}

// 加载更多日志
const loadMoreLogs = () => {
  if (hasMore.value && !loadingMore.value) {
    currentPage.value++
    fetchLogs(currentPage.value, true)
  }
}

// 下拉刷新
const refreshLogs = () => {
  currentPage.value = 1
  fetchLogs(1, false)
}

// 处理滚动事件
const handleScroll = () => {
  if (!timelineContainer.value) return

  const { scrollTop, clientHeight, scrollHeight } = timelineContainer.value

  // 当滚动到底部附近（10px范围内）时加载更多
  if (scrollHeight - scrollTop - clientHeight < 10) {
    loadMoreLogs()
  }
}

// 页面挂载时获取数据并设置滚动监听
onMounted(() => {
  fetchStats()
  loadInitialLogs()

  // 初始化运行时间计算
  calculateRunningTime()
  // 每秒更新一次运行时间
  const timer = setInterval(calculateRunningTime, 1000)

  // 确保DOM渲染完成后再设置滚动监听
  nextTick(() => {
    if (timelineContainer.value) {
      timelineContainer.value.addEventListener('scroll', handleScroll)
    }
  })

  // 清理函数
  return () => {
    clearInterval(timer)
    if (timelineContainer.value) {
      timelineContainer.value.removeEventListener('scroll', handleScroll)
    }
  }
})

// 页面激活时刷新数据
onActivated(() => {
  refreshLogs()
})

// 获取操作类型对应的标签样式
const getTagType = (type, hasError) => {
  if (hasError) return 'danger'

  const typeMap = {
    add: 'success',
    edit: 'primary',
    delete: 'danger',
    approve: 'success',
    view: 'info',
    register: 'warning',
    upload: 'warning',
    feedback: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取操作类型对应的文本
const getActionText = (type) => {
  const textMap = {
    add: '新增',
    edit: '编辑',
    delete: '删除',
    register: '登录'
  }
  return textMap[type] || '操作'
}

// 获取分类对应的标签样式
const getCategoryType = (category) => {
  const categoryMap = {
    user: 'primary',
    shop: 'success',
    dish: 'warning',
    ingredient: 'info',
    feedback: 'danger',
    other: 'default'
  }
  return categoryMap[category] || 'info'
}

// 获取分类对应的文本
const getCategoryText = (category) => {
  const textMap = {
    user: '管理员',
    shop: '商家',
    dish: '菜品',
    ingredient: '材料',
    feedback: '反馈',
    other: '其他'
  }
  return textMap[category] || '其他'
}

// 格式化数字显示
const formatNumber = (num) => {
  return num.toLocaleString()
}

// 格式化时间数字，确保两位数显示
const formatTimeNumber = (num) => {
  return num.toString().padStart(2, '0')
}
</script>

<template>
  <div class="dashboard">
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon user-icon">👥</div>
        <div class="stat-content">
          <h3>用户总数</h3>
          <p class="stat-number">{{ formatNumber(stats.totalUsers) }}</p>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon shop-icon">🏪</div>
        <div class="stat-content">
          <h3>商家数量</h3>
          <p class="stat-number">{{ formatNumber(stats.totalMerchants) }}</p>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon dish-icon">🍽️</div>
        <div class="stat-content">
          <h3>菜品总数</h3>
          <p class="stat-number">{{ formatNumber(stats.totalDishes) }}</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon visit-icon">📊</div>
        <div class="stat-content">
          <h3>总食材量</h3>
          <p class="stat-number">{{ formatNumber(stats.totalIngredients) }}</p>
        </div>
      </div>
    </div>

    <div class="charts-section">
      <!-- 小程序运行时间展示区域 -->
      <div class="runtime-card">
        <h3>小程序已运行时间</h3>
        <div class="launch-info">
          <p>启动时间: 2025年8月21日 10:30</p>
        </div>
        <div class="runtime-display">
          <div class="time-box">
            <div class="time-value">{{ runningTime.days }}</div>
            <div class="time-label">天</div>
          </div>
          <div class="time-separator">:</div>
          <div class="time-box">
            <div class="time-value">
              {{ formatTimeNumber(runningTime.hours) }}
            </div>
            <div class="time-label">时</div>
          </div>
          <div class="time-separator">:</div>
          <div class="time-box">
            <div class="time-value">
              {{ formatTimeNumber(runningTime.minutes) }}
            </div>
            <div class="time-label">分</div>
          </div>
          <div class="time-separator">:</div>
          <div class="time-box">
            <div class="time-value">
              {{ formatTimeNumber(runningTime.seconds) }}
            </div>
            <div class="time-label">秒</div>
          </div>
        </div>
      </div>

      <div class="recent-activity">
        <div class="activity-header">
          <h3>最近活动</h3>
          <el-button
            size="mini"
            :icon="Refresh"
            @click="refreshLogs"
            :loading="logLoading"
            class="refresh-btn"
          >
            刷新
          </el-button>
        </div>

        <div
          class="activity-timeline"
          @scroll="handleScroll"
          ref="timelineContainer"
        >
          <el-skeleton v-if="logLoading" :rows="8" :loading="logLoading" />

          <el-timeline v-else>
            <el-timeline-item
              v-for="(activity, index) in logData"
              :key="activity.id || index"
              :icon="activity.icon"
              :color="activity.color"
              :timestamp="activity.timestamp"
              :size="
                activity.type === 'delete' || activity.hasError
                  ? 'large'
                  : 'normal'
              "
            >
              <div class="activity-item-content">
                <div class="activity-text">{{ activity.content }}</div>
                <div class="activity-meta">
                  <el-tag
                    :type="getTagType(activity.type, activity.hasError)"
                    size="small"
                    class="activity-tag"
                  >
                    {{ getActionText(activity.type) }}
                  </el-tag>
                  <el-tag
                    :type="getCategoryType(activity.category)"
                    size="small"
                    effect="plain"
                    class="category-tag"
                  >
                    {{ getCategoryText(activity.category) }}
                  </el-tag>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>

          <div v-if="!logLoading && logData.length === 0" class="no-data">
            暂无日志数据
          </div>

          <!-- 加载更多指示器 -->
          <div v-if="loadingMore" class="loading-more">
            <span>加载中...</span>
          </div>

          <div
            v-if="!logLoading && !hasMore && logData.length > 0"
            class="no-more"
          >
            已显示全部日志
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.dashboard {
  padding: 20px;

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 24px;
    margin-bottom: 32px;

    .stat-card {
      background: #fff;
      border-radius: 12px;
      padding: 24px;
      border: 1px solid #e2e8f0;
      display: flex;
      align-items: center;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
      }

      .stat-icon {
        font-size: 2.5rem;
        margin-right: 20px;
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;

        &.visit-icon {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }

        &.user-icon {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.shop-icon {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.dish-icon {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
      }

      .stat-content {
        flex: 1;

        h3 {
          font-size: 0.9rem;
          color: #718096;
          margin-bottom: 4px;
          font-weight: 500;
        }

        .stat-number {
          font-size: 2rem;
          font-weight: 700;
          color: #1a202c;
          margin-bottom: 4px;
        }
      }
    }
  }

  .charts-section {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;

    .runtime-card,
    .recent-activity {
      background: #fff;
      border-radius: 12px;
      padding: 24px;
      border: 1px solid #e2e8f0;

      h3 {
        font-size: 1.2rem;
        color: #1a202c;
        margin-bottom: 20px;
        font-weight: 600;
      }
    }

    .runtime-card {
      display: flex;
      flex-direction: column;

      .launch-info {
        color: #718096;
        margin-bottom: 24px;
        font-size: 0.9rem;
        padding-bottom: 16px;
        border-bottom: 1px solid #f1f5f9;
      }

      .runtime-display {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 16px;
        margin-top: 60px;
        padding: 24px 0;

        .time-box {
          display: flex;
          flex-direction: column;
          align-items: center;

          .time-value {
            font-size: 2.5rem;
            font-weight: 700;
            color: #1a202c;
            line-height: 1;
            padding: 12px 16px;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            border-radius: 8px;
            min-width: 80px;
            text-align: center;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
          }

          .time-label {
            margin-top: 8px;
            font-size: 0.85rem;
            color: #718096;
            font-weight: 500;
          }
        }

        .time-separator {
          font-size: 2rem;
          font-weight: bold;
          color: #cbd5e1;
          animation: blink 1s infinite;
        }
      }
    }

    .activity-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .refresh-btn {
      padding: 4px 8px;
    }

    .activity-timeline {
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;
      position: relative;

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-track {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.1);
        border-radius: 2px;

        &:hover {
          background: rgba(0, 0, 0, 0.2);
        }
      }

      .activity-item-content {
        .activity-text {
          color: #1a202c;
          font-size: 0.9rem;
          line-height: 1.5;
          margin-bottom: 8px;
        }

        .activity-text.error {
          color: #f56c6c;
        }

        .activity-meta {
          display: flex;
          gap: 8px;

          .activity-tag {
            font-size: 0.75rem;
            border-radius: 4px;
          }

          .category-tag {
            font-size: 0.75rem;
            border-radius: 4px;
          }
        }
      }

      .no-data {
        text-align: center;
        padding: 20px;
        color: #718096;
        background-color: #f7fafc;
        border-radius: 8px;
      }

      .loading-more {
        text-align: center;
        padding: 16px;
        color: #718096;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
      }

      .no-more {
        text-align: center;
        padding: 16px;
        color: #718096;
        font-size: 0.9rem;
      }

      :deep(.el-timeline-item__timestamp) {
        color: #718096;
        font-size: 0.8rem;
        font-weight: 500;
      }

      :deep(.el-timeline-item__icon) {
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      :deep(.el-timeline-item__content) {
        padding-bottom: 16px;
      }
    }
  }
}

// 时间分隔符闪烁动画
@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.4;
  }
}
</style>
